<!-- https://blog.csdn.net/qq_42483780/article/details/125003251 -->

<template>
	<view class="main">
		<view class="type1" @click="funConnectBluetooth">环境信息</view>
		<view class="type2">提供环境温度、湿度等数据</view>
		
		<view class="type4" >温度</view>
		<view class="type3" > 
			<view class="type5">
				<view class="type6">T</view>
				<view class="type7">测量温度</view>
				<view class="type8">温湿度传感器</view>
				<view class="type9"> {{exportDataTemp}} </view>
				<view class="type10"> ℃</view>
			</view>
		</view>
		
		<view class="type4" @click="funSandBleMessage()">湿度</view>
		<view class="type3"> 
			<view class="type5">
				<view class="type6">H</view>
				<view class="type7">测量湿度</view>
				<view class="type8">温湿度传感器</view>
				<view class="type9"> {{exportDataHum}} </view>
				<view class="type10"> %</view>
			</view>
		</view>
		
		<view class="type4" @click="funSandBleMessage()">光照</view>
		<view class="type3"> 
			<view class="type5">
				<view class="type6">L</view>
				<view class="type7">日光检测</view>
				<view class="type8">光照传感器</view>
				<view class="type9"> {{exportDataHum}} </view>
				<view class="type10">lum</view>
			</view>
		</view>
		
		<view class="type4" @click="funSandBleMessage()">二氧化碳</view>
		<view class="type3"> 
			<view class="type5">
				<view class="type6">C</view>
				<view class="type7">Co2</view>
				<view class="type8">二氧化碳传感器</view>
				<view class="type9"> {{exportDataHum}} </view>
				<view class="type10"> pm</view>
			</view>
		</view>
		
		<view class="type4" @click="funSandBleMessage()"> 人体传感器</view>
		<view class="type3"> 
			<view class="type5">
				<view class="type6">P</view>
				<view class="type7">人体</view>
				<view class="type8">存在检测</view>
				<view class="type9"> {{exportDataHum}} </view>
				<view class="type10"> @</view>
			</view>
		</view>

		<view class="type4" @click="gotoZhinneg">自动</view>
		<view class="type3" @click="gotoZhinneg"> 
			<view class="type5">
				<view class="type6">E</view>
				<view class="type7">智能场景 </view>
				<view class="type8">更多设备联动场景</view>
				<view class="type11">></view>
				<!-- <view class="type10"> %</view> -->
			</view>
		</view>

	</view>
	
</template>

<script>
	var devicesList = []; //保存搜索到的蓝牙设备列表
	var tianBle = []; // 保存在蓝牙列表中找到的设备
	var server = []; //保存手表蓝牙上的每一个服务信息
	var characteristic = []; //保存手表蓝牙上的每一个服务信息的属性值
	
	export default {
		data() {
			return {
				title: 'Hello word',
				exportDataTemp:12,
				exportDataHum:89,
			}
		},
		onLoad() {
			var that = this;
			that.initPage()
		},
		methods: {
			
			initPage() {
				uni.request({
					url: 'https://101.34.205.32/tian', //仅为示例，并非真实接口地址。
					sslVerify: false,
				
				    success: (res) => {
				        console.log(res.data);
				        obj = JSON.parse(res.data);
						console.log(obj["hum"]);
				    },
					fail(res) {
						console.log(res);
					}
				});
			},

			init_BLE_device(){
				console.log("执行刷新")
				uni.openBluetoothAdapter({
					success(res) {
						console.log("蓝牙初始化成功",res)
					},
					fail(res) {
						console.log("蓝牙初始化失",res)
						uni.showModal({
							title:"提示",
							content:'请打开手机蓝牙进行操作'
						})
					}
				}),
								
				uni.startBluetoothDevicesDiscovery({
					//services:['1801'],pages/index/index
					success(res) {
						console.log("搜索蓝牙得到的结果",res)
					},
					fail(res) {
						console.log("搜索蓝牙得到的错误结果",res)
					}
				}),
								
				uni.onBluetoothDeviceFound(function(data){
					//console.log(data.devices) //打印每一个获取到的蓝牙信息，
					devicesList.push(data.devices[0]) //向对象内添加一个新的元素
				})
			},
			
			funConnectBluetooth(){
				
				uni.showLoading({
					title: '连接蓝牙中'
				});
				
				console.log('连接手表蓝牙')
				
				let that = this; //更改this作用域
				let fineFlag = 0;
				this.init_BLE_device()
				
				setTimeout(function(){
					
					//刷新获得蓝牙列表
					uni.stopBluetoothDevicesDiscovery({ //停止刷新设备
					  success(res) {
						console.log("停止刷新",res)
						console.log("显示列表",devicesList)
						setTimeout(function(){
							uni.hideLoading();
						},5000)
						//循环遍历刷新到的蓝牙列表
						for(var key in devicesList){
							console.log("蓝牙名称:",devicesList[key].name)
							if(devicesList[key].name == "xiaogua"){
								tianBle = devicesList[key]
								console.log("完成",tianBle.deviceId)	
								fineFlag = 1;
								//连接蓝牙设备
								uni.createBLEConnection({
									
									// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
									deviceId:tianBle.deviceId,
									success(res) {
									console.log('连接成功 createBLEConnection:',res, tianBle.deviceId)
									fineFlag = 1;
									uni.showLoading({
										title: 'xiaogua连接成功'
									});
									setTimeout(function(){
										uni.hideLoading();
									},1500)
								  }
								})
								
								setTimeout(function(){
									//获取蓝牙设备的每一个服务
									uni.getBLEDeviceServices({
									  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
									  deviceId:tianBle.deviceId,
									  success(res) {
										console.log('device services:', res.services)
										server = res.services
									  }
									})	
								},2000)
								
								setTimeout(function(){
									for(let i=0; i<server.length; i++){
										//获取具体的每个服务信息的属性值
										uni.getBLEDeviceCharacteristics({
											// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
											deviceId:tianBle.deviceId,
											// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
											serviceId:server[i].uuid,
												
											success(res) {	
												characteristic.push(res.characteristics)
												console.log('device getBLEDeviceCharacteristics:', res.characteristics)
												
												uni.hideLoading(); // 关闭弹窗
									
												setTimeout(function(){
													that.updateNotify();
												},200)
											}
										})	
									}
								},3000)
							}
						}
						if (fineFlag == 0) {
							uni.showModal({
									title: '提示',
									content: '需要重新扫描蓝牙。请确保蓝牙设备正常打开',
									success: function(res) {
									if (res.confirm) {
									    that.funConnectBluetooth();
									} 
									else {
										uni.hideLoading();
										// 执行取消后的操作
										uni.navigateTo({ // （关闭当前页面，跳转到其他页面）
										    url:'./../index/index'
										});
									}
								}
							})
							console.log("连接失败，需要重试");
							
						}
					  }
					})
				},3000);
				
				
			},		
 			
			// 启用低功耗蓝牙设备特征值变化时的notify功能
			updateNotify() {
				let that = this
				uni.showLoading({
					title: '获取蓝牙数据'
				});
				console.log("启用低功耗蓝牙设备特征值变化时的notify功能");
				
				uni.notifyBLECharacteristicValueChange({
					deviceId: tianBle.deviceId,
					serviceId:"0000FFF0-0000-1000-8000-00805F9B34FB",
					characteristicId:"0000FFF1-0000-1000-8000-00805F9B34FB",
					state: true,
					success: (res) => {
						console.log(res);
						if (res.errMsg == "notifyBLECharacteristicValueChange:ok") {
							console.log("开启消息监听------", res);
							setTimeout(function(){
								uni.hideLoading();
							},1000);
							this.listenMessage();

							setTimeout(function(){
								that.funSandBleMessage();
							},500)
							
						}
					},
					fail: (res) => {
					  console.log("失败1--------", res);
					},
				});
			},
			
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
			  const hexArr = Array.prototype.map.call(
				new Uint8Array(buffer),
				function (bit) {
				  return ('00' + bit.toString(16)).slice(-2)
				}
			  )
			  return hexArr.join('')
			},
		
			// 将16进制的内容转成我们看得懂的字符串内容
			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim();
				var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
						alert("存在非法字符!");
						return "";
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
						curCharCode = parseInt(rawStr.substr(i, 2), 16);
						resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.join("");
			},
			//监听发送过来的消息
			listenMessage() {
				let that = this
				uni.onBLECharacteristicValueChange((res) => {
				console.log("发送过来的数据---------", res);
						// 结果里有个value值，该值为 ArrayBuffer 类型，所以在控制台无法用肉眼观察到，必须将该值转换为16进制
						let resHex = that.ab2hex(res.value)
						// console.log("resHex:", resHex);
						// 最后将16进制转换为ascii码，就能看到对应的结果
						let result = that.hexCharCodeToStr(resHex)
						// console.log("get data:", result)
						const obj = JSON.parse(result);
						
						if (obj["T"] != null) {
							this.exportDataTemp = obj["T"];
							getApp().globalData.dataTemp = this.exportDataTemp;
							console.log("get ble data:", obj["T"], getApp().globalData.dataTemp);
						}
						if (obj["H"] != null) {
							this.exportDataHum = obj["H"];
							getApp().globalData.dataHum = this.exportDataHum;
							console.log("get ble data:", obj["H"]);
						}
				})
			},
	
			funSandBleMessage() {
				
				const buffer = new ArrayBuffer(9) //分配1个字节的连续内存区域。 
				const dataView = new DataView(buffer)
				// 4C 56 42 45 47 49 4E 
				dataView.setUint8(0, 0x4C)
				dataView.setUint8(1, 0x56)
				dataView.setUint8(2, 0x42)
				dataView.setUint8(3, 0x45)
				dataView.setUint8(4, 0x47)
				dataView.setUint8(5, 0x49)
				dataView.setUint8(6, 0x4E)
				dataView.setUint8(7, 0x0D)
				dataView.setUint8(8, 0x0A)
			
				getApp().globalData.dataDeviceID = tianBle.deviceId;
				// for( let i=2; i<20; i++){
				// 	dataView.setUint8(i, HexAn[i-2])
				// }
				
				//改变指定服务属性的uuid数值
				uni.writeBLECharacteristicValue({
				  // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
				  deviceId:tianBle.deviceId,
				  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
				  serviceId:"0000FFF0-0000-1000-8000-00805F9B34FB",
				  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
				  characteristicId:"0000FFF1-0000-1000-8000-00805F9B34FB",
				  // 这里的value是ArrayBuffer类型
				  value: buffer,
				  success(res) {
					console.log('writeBLECharacteristicValue success', res.errMsg)
					
				  },
				  
				  fail(res) {
					 console.log(res)
					 uni.hideLoading();
					 uni.showModal({
						 title: '提示',
						 content: '传输失败',
						 success: function (res) {
							 if (res.confirm) {
								 console.log('确定');
							 }
						 }
					 });
				  }
				})
			},
			
			loadBle() {
				var that = this;
				uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
					success: function(res) {
						console.log(res)
						uni.showToast({
							title: '初始化成功',
							icon: 'success',
							duration: 800
						})
						that.findBlue(); //2.0
					},
					fail: function(res) { //如果手机上的蓝牙没有打开，可以提醒用户
						uni.showToast({
							title: '请打开蓝牙',
							type: 'error',
							icon: 'none'
						});
					}
				})
			},	
			findBlue() {
				setTimeout(()=>{
					  uni.getBLEDeviceServices({
					    // deviceId,
					    success(res) {
					      console.log("设备的服务：", res.services);
					    },
					    fail(err) {
					      console.log("获取服务失败：", err);
					    },
					  });
				  }, 5000)
			},
			getBlue() {
				var that = this
				//uni.getBluetoothDevices获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
				uni.getBluetoothDevices({
					success: function(res) {
						if (res.devices[0]) {
						  console.log(ab2hex(res.devices[0].advertisData))
						}
						uni.hideLoading();
						console.log(res)
						that.BluetoothList = res.devices
						console.log(that.BluetoothList)
						console.log(res.devices)
						//将BluetoothList遍历给用户，当用户点击连接某个蓝牙时调用4.0
					},
					fail: function() {
						console.log("搜索设备失败")
					}
				})
			},
			button1() {
				var that = this;
				that.loadBle()
			},
			gotoZhexian() {
				console.log("开始连接打印机:");
				// 1.不传参
				uni.navigateTo({ 
				    url:'../zhexian/zhexian'
				});
			},
			gotoZhinneg() {
				console.log("跳转界面:");
				uni.navigateTo({
				    url:'./zhineng'
				});
			}
		},
		
	}
</script>

<style>
	.type1 {
		font-size: 30px; 
		margin-left:3%;
	}
	
	.type2 {
		font-size: 20px;
		color: #656565;
		margin-left:3%;
	}
	
	.type3 {
		display: flex;
		justify-content: center; /* 水平居中 */
		height: 80px;
	}
	
	.type4 {
		font-size: 10px;
		color: #656565;
		margin-top: 40px;
		margin-left: 5%;
	}
	
	.type5 {
		border-radius: 15px;  /* 统一圆角 */
		background: #ffffff;  /* 背景色或边框 */
		width: 92%; 
		height: 100px;
		margin-top: 1%;
		margin-left: 0%;	
	}
	
	.type6 {
		display: flex;
		font-size: 35px;
		border-radius: 15px;  /* 统一圆角 */
		width: 50px; 
		height: 50px;
		justify-content: center; /* 水平居中 */
		color: #eaeaea;
		background-color: #4dbae1;
		margin-top: 20px;
		margin-left: 20px;
	}
	
	.type7 {
		font-size: 17px; 
		margin-left: 85px;
		margin-top: -45px;
	}
	
	.type8 {
		font-size: 15px; 
		margin-left: 85px;
		margin-top: 0px;
		color: #969696;
	}
	
	.type9 {
		font-size: 30px; 
		margin-left: 70%;
		margin-top: -12%;
		color: #000000;
	}
	
	.type10 {
		font-size: 30px;
		margin-left: 82%;
		margin-top: -11%;
		color: #969696;
	}
	
	.type11 {
		font-size: 251%;
		margin-left: 290px;
		margin-top: -50px;
		color: #d0d0d0;
	}
</style>